/*
 * @Author: limit
 * @Date: 2021-04-02 11:14:23
 * @LastEditTime: 2021-07-20 13:31:30
 * @LastEditors: limit
 * @FilePath: /sim-card-platform/src/directive/index.js
 * @Description: 由limit创建！
 */

import Vue from "vue";

Vue.directive('phone', {
    inserted(el, binding) {
        el.addEventListener('input', function(e) {
            const reg = /\d/;
            const oldValue = e.target.value;
            const value = e.data;
            if (!value) return;
            if (!reg.test(value) || oldValue.length > 11) e.target.value = oldValue.slice(0, oldValue.length - value.length);
        })
    }
})

Vue.directive('idcard', {
    inserted(el, binding) {
        el.addEventListener('input', function(e) {
            const oldValue = e.target.value;
            const value = e.data;
            const reg = /\d/;
            if (oldValue.length == 18 || oldValue.length == 15 &&
                (value.endsWith('x') || value.endsWith('X'))) return;
            if (!reg.test(value) || oldValue.length > 18) e.target.value = oldValue.slice(0, oldValue.length - value.length);
        })
    }
})

Vue.directive('dbClick', {
    inserted(el, binding) {
        el.addEventListener('click', e => {
            const iEle = document.createElement('i');
            iEle.classList = 'el-icon-loading'
            if (!el.disabled) {
                const oldValue = el.children[0].innerText;
                el.disabled = true;
                el.children[0].innerText = binding.value || '保存中...';
                el.insertBefore(iEle, el.firstElementChild);
                el.style.cursor = 'wait';
                setTimeout(() => {
                    iEle.remove();
                    el.style.cursor = 'pointer';
                    el.disabled = false;
                    el.children[0].innerText = oldValue;
                }, 1500)
            }
        })
    }
})
Vue.directive('downLoad', {
    bind(el, binding) {
        el.addEventListener('click', () => {
            console.log(binding.value) // url
            const a = document.createElement('a')
                //   let url = baseUrl + binding.value // 若是不完整的url则需要拼接baseURL
            const url = binding.value.file // 完整的url则直接使用
            const name = binding.value.fileName
                // 这里是将url转成blob地址，
            fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
                a.href = URL.createObjectURL(blob)
                console.log(a.href)
                a.download = name // 下载文件的名字
                    // a.download = url.split('/')[url.split('?').length - 1] //  // 下载文件的名字
                document.body.appendChild(a)
                a.click()
            })
        })
    }
})